from flask import Blueprint, request, jsonify
from src.models.database import db, IndustryData
from src.models.metaso_data import MetasoQueryData, MetasoWebpageData
from src.services.metaso_service import MetasoService
from datetime import datetime
import json

industry_bp = Blueprint('industry', __name__)
metaso_service = MetasoService()

@industry_bp.route('/crawl', methods=['POST'])
def start_crawl_task():
    """启动行业数据查询任务 - 异步执行Metaso API查询"""
    try:
        # 启动四个板块的批量查询（异步执行）
        batch_result = metaso_service.query_industry_data_batch()
        
        return jsonify({
            'code': 200,
            'message': '✅ 行业数据查询任务已启动，正在后台异步执行',
            'data': {
                'batch_id': batch_result['batch_id'],
                'tasks': batch_result['tasks'],
                'total_tasks': batch_result['total_tasks'],
                'status': 'running',
                'note': '任务已在后台启动，请使用task_id查询具体进度和结果'
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'启动查询失败: {str(e)}'}), 500

@industry_bp.route('/crawl/status/<batch_id>', methods=['GET'])
def get_batch_status(batch_id):
    """获取批量查询任务状态"""
    try:
        # 这里需要从请求参数或者数据库中获取task_ids
        # 简化实现，返回最近的查询状态
        recent_queries = metaso_service.get_all_queries(limit=10)
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'batch_id': batch_id,
                'queries': recent_queries
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询状态失败: {str(e)}'}), 500

@industry_bp.route('/metaso/query', methods=['POST'])
def start_single_query():
    """启动单个Metaso查询"""
    try:
        data = request.get_json() or {}
        query_text = data.get('query_text', '')
        
        if not query_text:
            return jsonify({'code': 400, 'message': '查询文本不能为空'}), 400
        
        task_id = metaso_service.start_query_task(query_text)
        
        return jsonify({
            'code': 200,
            'message': '查询任务已启动',
            'data': {
                'task_id': task_id,
                'status': 'running'
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'启动查询失败: {str(e)}'}), 500

@industry_bp.route('/metaso/query/<task_id>', methods=['GET'])
def get_query_status(task_id):
    """获取查询任务状态"""
    try:
        status = metaso_service.get_query_task_status(task_id)
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': status
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询状态失败: {str(e)}'}), 500

@industry_bp.route('/metaso/data/<query_id>', methods=['GET'])
def get_query_data(query_id):
    """获取查询结果数据"""
    try:
        data = metaso_service.get_query_data(query_id)
        
        if not data:
            return jsonify({'code': 404, 'message': '查询数据不存在'}), 404
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': data
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取数据失败: {str(e)}'}), 500

@industry_bp.route('/data', methods=['GET'])
def get_industry_data():
    """获取行业数据"""
    try:
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 20, type=int)
        source = request.args.get('source')
        industry = request.args.get('industry')
        
        query = IndustryData.query.filter_by(status='active')
        
        if source:
            query = query.filter(IndustryData.source == source)
        if industry:
            query = query.filter(IndustryData.industry == industry)
        
        query = query.order_by(IndustryData.crawl_date.desc())
        
        pagination = query.paginate(
            page=page,
            per_page=page_size,
            error_out=False
        )
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'items': [item.to_dict() for item in pagination.items],
                'total': pagination.total,
                'page': page,
                'page_size': page_size,
                'pages': pagination.pages
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@industry_bp.route('/data/<int:data_id>', methods=['GET'])
def get_industry_data_detail(data_id):
    """获取行业数据详情"""
    try:
        data_item = IndustryData.query.get(data_id)
        
        if not data_item:
            return jsonify({'code': 404, 'message': '数据不存在'}), 404
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': data_item.to_dict()
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@industry_bp.route('/data/upload', methods=['POST'])
def upload_industry_document():
    """手动上传行业文档"""
    try:
        if 'file' not in request.files:
            return jsonify({'code': 400, 'message': '未找到上传文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'code': 400, 'message': '未选择文件'}), 400
        
        # 获取额外参数
        source = request.form.get('source', '手动上传')
        industry = request.form.get('industry', '医药')
        title = request.form.get('title', file.filename)
        
        # 处理文档上传 - 暂时不支持，返回提示信息
        result = {
            'message': '文档上传功能暂时不支持，请使用Metaso API查询功能',
            'filename': file.filename,
            'source': source,
            'industry': industry
        }
        
        return jsonify({
            'code': 200,
            'message': '文档上传成功',
            'data': result
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'上传失败: {str(e)}'}), 500

@industry_bp.route('/data/search', methods=['GET'])
def search_industry_data():
    """搜索行业数据"""
    try:
        keyword = request.args.get('keyword', '')
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 20, type=int)
        
        if not keyword:
            return jsonify({'code': 400, 'message': '缺少搜索关键词'}), 400
        
        # 在标题和内容中搜索
        query = IndustryData.query.filter(
            db.or_(
                IndustryData.title.contains(keyword),
                IndustryData.content.contains(keyword)
            )
        ).filter_by(status='active')
        
        query = query.order_by(IndustryData.crawl_date.desc())
        
        pagination = query.paginate(
            page=page,
            per_page=page_size,
            error_out=False
        )
        
        return jsonify({
            'code': 200,
            'message': '搜索成功',
            'data': {
                'items': [item.to_dict() for item in pagination.items],
                'total': pagination.total,
                'page': page,
                'page_size': page_size,
                'pages': pagination.pages,
                'keyword': keyword
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'搜索失败: {str(e)}'}), 500

@industry_bp.route('/sources', methods=['GET'])
def get_data_sources():
    """获取数据源列表"""
    try:
        sources = db.session.query(IndustryData.source).distinct().all()
        source_list = [source[0] for source in sources]
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': source_list
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@industry_bp.route('/statistics', methods=['GET'])
def get_industry_statistics():
    """获取行业数据统计"""
    try:
        stats = metaso_service.get_statistics()
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': stats
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@industry_bp.route('/metaso/queries', methods=['GET'])
def get_all_metaso_queries():
    """获取所有Metaso查询记录"""
    try:
        limit = request.args.get('limit', 50, type=int)
        queries = metaso_service.get_all_queries(limit=limit)
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'queries': queries,
                'total': len(queries)
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@industry_bp.route('/sectors/data', methods=['GET'])
def get_sectors_data():
    """获取四个板块的最新数据"""
    try:
        # 获取四个板块的最新查询结果
        sectors = ['pharma_formulations', 'pharma_apis', 'plant_protection', 'animal_health']
        sector_names = {
            'pharma_formulations': '人药制剂板块',
            'pharma_apis': '人药原料药板块', 
            'plant_protection': '植保板块',
            'animal_health': '动保板块'
        }
        
        results = {}
        for sector_id in sectors:
            # 获取该板块最新的完成查询
            latest_query = MetasoQueryData.query.filter_by(
                sector_id=sector_id,
                status='completed'
            ).order_by(MetasoQueryData.created_at.desc()).first()
            
            if latest_query:
                query_dict = latest_query.to_dict(include_sources=True)
                # 确保包含新的AI分析字段
                results[sector_id] = {
                    'sector_name': sector_names.get(sector_id, sector_id),
                    'data': query_dict
                }
            else:
                results[sector_id] = {
                    'sector_name': sector_names.get(sector_id, sector_id),
                    'data': None,
                    'message': '暂无数据'
                }
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'sectors': results,
                'last_updated': datetime.now().isoformat()
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

